package com.fable.sp.core.widgets;

import com.fable.sp.core.annotation.RenderMode;
import com.fable.sp.core.domain.PersistentField;
import com.fable.sp.core.domain.WidgetInstance;
import com.fable.sp.core.widget.*;

/**
 * .
 *
 * @author stormning on 16/8/8.
 */
public abstract class PersistentWidget extends SimpleWidget implements Persistentable {

    private PersistentField persistentField;

    public PersistentWidget() {
        this.persistentField = defineField();
    }

    @RenderMode(name = RENDER_MODE_PREFERENCE)
    public void preference(RenderRequest request, RenderResponse response) {

    }

    @RenderMode(name = RENDER_MODE_EDIT)
    public void edit(RenderRequest request, RenderResponse response) {
    }

    @RenderMode(name = RENDER_MODE_VIEW)
    public void view(RenderRequest request, RenderResponse response) {
    }

    @Override
    public void beforeRender(WidgetRequest request, WidgetResponse widgetResponse) {
        request.setAttribute("field", getField(request));
    }

    @Override
    public PersistentField getField(WidgetRequest request) {
        final WidgetInstance instance = request.getWidgetInstance();
        PersistentField copy = new PersistentField() {
            @Override
            public String getName() {
                return PersistentField.FIELD_NAME_PREFIX + instance.getId();
            }
        };
        copy.setSupportTypes(persistentField.getSupportTypes());
        copy.setName(persistentField.getName());
        copy.setLength(persistentField.getLength());
        copy.setValue(request.getFieldValue());
        return copy;
    }
}
